#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <string.h>

#include "slowcat.h"

/*
 * 实现cat功能
 * 多线性的方式，实现每秒读取指定长度的数据
 * */

#define BUFFSIZE 128
#define CPS 10
#define BURST 100

int main(int argc, char **argv)
{
	// output = 1; 表示向终端输出读出来的文本信息
	int input, output = 1;
	char buf[BUFFSIZE];
	int len, ret, pos, size;
	
	job_t * job;

	if(argc != 2){
		fprintf(stderr, "Usage.....\n");
		exit(1);
	}
	
	job = job_init(CPS,BURST);
	if(job == NULL)
	{
		fprintf(stderr, "job_init() failed! \n");
		exit(1);
	}

	do{
		input = open(argv[1], O_RDONLY);
		if(input < 0){
			if(errno != EINTR){
				perror("open()");
				exit(1);
			}
		}
	} while(input < 0);
	
	while(1){

		size = job_fetchtoken(job, BUFFSIZE);
		if(size < 0)
		{
			fprintf(stderr, "job_fetchtoken() is empty: %s \n", strerror(-size));
		}
		len = read(input, buf, BUFFSIZE);
		if(len < 0){
			if(errno == EINTR){
				continue;
			}
			perror("read()");
			break;
		} else if(len == 0){
			break;
		}
		
		if(size - len > 0)
		{
			job_returntoken(job, size - len);
		}

		pos = 0;
		while(len > 0){
			ret = write(output, buf + pos, len);
			if(ret < 0){
				if(errno == EINTR){
					continue;
				}
				perror("write()");
				exit(1);
			}
			pos += ret; // 记录文件写入位置
			len -= ret; // 一次写不完，继续写入
		}
	}

	close(input);

	job_destory(job);

	exit(0);
}
